package com.chengxiaoxiao.web.controller;

import com.chengxiaoxiao.commons.Page;
import com.chengxiaoxiao.constant.Constants;
import com.chengxiaoxiao.domain.BlackList;
import com.chengxiaoxiao.domain.Classes;
import com.chengxiaoxiao.domain.Users;
import com.chengxiaoxiao.service.BlackListService;
import com.chengxiaoxiao.service.ClassesService;
import com.chengxiaoxiao.service.UsersService;
import com.chengxiaoxiao.service.impl.BlackListServiceImpl;
import com.chengxiaoxiao.service.impl.ClassesServiceImpl;
import com.chengxiaoxiao.service.impl.UsersServiceImpl;
import com.chengxiaoxiao.utils.JSONUtils;
import com.chengxiaoxiao.utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.HashMap;

//@WebServlet("/manager/UserServlet")
public class UserServlet extends HttpServlet {

    private UsersService service = new UsersServiceImpl();
    private ClassesService classesService = new ClassesServiceImpl();
    private BlackListService blackListService = new BlackListServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setHeader("Content-Type", "application/json");
        String op = request.getParameter("op");


        if ("login".equals(op)) {
            login(request, response);
        } else if ("updatepwd".equalsIgnoreCase(op)) {
            updatePwd(request, response);
        } else if ("personinfo".equalsIgnoreCase(op)) {
            showPersonInfo(request, response);
        } else if ("listuser".equalsIgnoreCase(op)) {
            listUser(request, response);
        } else if ("blacklist".equalsIgnoreCase(op)) {
            blacklist(request, response);
        } else if ("showblack".equalsIgnoreCase(op)) {
            showBlack(request, response);
        } else if ("deleteBlack".equalsIgnoreCase(op)) {
            deleteBlack(request, response);
        } else if ("showuser".equalsIgnoreCase(op)) {
            showUser(request, response);
        } else if ("putBlack".equalsIgnoreCase(op)) {
            putBlack(request, response);
        }
        else if("blackuser".equalsIgnoreCase(op))
        {
            blackUser(request,response);
        }


    }

    /**
     * 拉黑操作，接收拉黑理由
     * @param request
     * @param response
     */
    private void blackUser(HttpServletRequest request, HttpServletResponse response) {

        String id = request.getParameter("id");
        int ids = Integer.parseInt(id);
        String cause = request.getParameter("cause");

        HashMap<String,String> map = new HashMap<>();
        if(StringUtils.isNullOrEmpty(cause))
        {
            map.put(Constants.JSON_RESPONSE_KEY_STATUS,"error");
            map.put(Constants.JSON_RESPONSE_KEY_ERRORMSG,"请输入拉黑理由");
            JSONUtils.toJson(response,map);
            return;
        }

        service.black(ids,cause);


        map.put(Constants.JSON_RESPONSE_KEY_STATUS,"ok");
        map.put(Constants.JSON_RESPONSE_KEY_ERRORMSG,"用户已被拉黑");
        JSONUtils.toJson(response,map);
    }

    /**
     * @param request
     * @param response
     */
    private void putBlack(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        String id = request.getParameter("id");
        int ids = Integer.parseInt(id);
        Users users = service.getUserAndExtra(ids);
        request.setAttribute("user",users);
        request.getRequestDispatcher("/user/putblack.jsp").forward(request, response);
    }

    /**
     * 显示用户的详细信息
     *
     * @param request
     * @param response
     */
    private void showUser(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        String id = request.getParameter("id");
        int ids = Integer.parseInt(id);
        Users user = service.getAllUserInfo(ids);

        request.setAttribute("user", user);
        request.getRequestDispatcher("/user/showuser.jsp").forward(request, response);
    }

    /**
     * 显示所有用户
     *
     * @param request
     * @param response
     */
    private void listUser(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String num = request.getParameter("num");
        String snum = request.getParameter("snum");

        if (!StringUtils.isNullOrEmpty(snum)) {
            Page page = service.getPageLikeSNum(num, snum);
            page.setUrl("/manager/UserServlet?op=blacklist");
            request.setAttribute("snum", snum);
            request.setAttribute("page", page);
            request.getRequestDispatcher("/user/listuser.jsp").forward(request, response);
        } else {
            Page page = service.getListPage(num);
            page.setUrl("/manager/UserServlet?op=blacklist");
            request.setAttribute("page", page);
            request.getRequestDispatcher("/user/listuser.jsp").forward(request, response);
        }
    }

    /**
     * 删除黑名单用户
     *
     * @param request
     * @param response
     */
    private void deleteBlack(HttpServletRequest request, HttpServletResponse response) {

        String id = request.getParameter("id");
        int ids = Integer.parseInt(id);
        blackListService.delete(ids);


        HashMap<String, String> map = new HashMap<>();
        map.put(Constants.JSON_RESPONSE_KEY_STATUS, "ok");
        map.put(Constants.JSON_RESPONSE_KEY_ERRORMSG, "删除成功");
        JSONUtils.toJson(response, map);

    }

    /**
     * 获取黑名单用户详细信息
     *
     * @param request
     * @param response
     */
    private void showBlack(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        String id = request.getParameter("id");

        int ids = 0;
        if (!StringUtils.isNullOrEmpty(id)) {
            ids = Integer.parseInt(id);
        }

        BlackList blackList = blackListService.getbyId(ids);
        request.setAttribute("black", blackList);
        request.getRequestDispatcher("/user/showblack.jsp").forward(request, response);


    }

    /**
     * 黑名单
     *
     * @param request
     * @param response
     */
    private void blacklist(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        String num = request.getParameter("num");
        String snum = request.getParameter("snum");

        if (!StringUtils.isNullOrEmpty(snum)) {
            Page page = blackListService.getPageLikeSNum(num, snum);
            page.setUrl("/manager/UserServlet?op=blacklist");
            request.setAttribute("snum", snum);
            request.setAttribute("page", page);
            request.getRequestDispatcher("/user/blacklist.jsp").forward(request, response);
        } else {
            Page page = blackListService.getListPage(num);
            page.setUrl("/manager/UserServlet?op=blacklist");
            request.setAttribute("page", page);
            request.getRequestDispatcher("/user/blacklist.jsp").forward(request, response);
        }


    }

    /**
     * 查看个人信息
     *
     * @param request
     * @param response
     */
    private void showPersonInfo(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        HttpSession session = request.getSession();
        Users user = (Users) session.getAttribute(Constants.SESSION_USER_MODEL);

        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }

        Users userAll = service.getUserAndExtra(user.getId());

        Classes classes = classesService.getbyId(userAll.getClassesId());
        if (classes.getCollegeId() != 0) {
            Classes college = classesService.getbyId(classes.getCollegeId());
            classes.setClasses(college);
        }
        request.setAttribute(Constants.REQUEST_CLASSES_MODEL_PERSONINFO, classes);
        request.setAttribute(Constants.REQUEST_USERS_MODEL_PERSONINFO, userAll);
        request.getRequestDispatcher("/personinfo.jsp").forward(request, response);

    }

    /**
     * 修改密码
     *
     * @param request
     * @param response
     */
    private void updatePwd(HttpServletRequest request, HttpServletResponse response) {
        String oldpwd = request.getParameter("oldpwd");
        String newpwd = request.getParameter("newpwd");

        HashMap<String, String> map = new HashMap<>();
        if (StringUtils.isNullOrEmpty(oldpwd) || StringUtils.isNullOrEmpty(newpwd)) {
            map.put(Constants.JSON_RESPONSE_KEY_STATUS, "error");
            map.put(Constants.JSON_RESPONSE_KEY_ERRORMSG, "请输入密码");
            JSONUtils.toJson(response, map);
            return;
        }

        HttpSession session = request.getSession();
        Users user = (Users) session.getAttribute(Constants.SESSION_USER_MODEL);

        if (user == null) {

            return;
        }
        if (!oldpwd.equalsIgnoreCase(user.getPassword())) {
            map.put(Constants.JSON_RESPONSE_KEY_STATUS, "error");
            map.put(Constants.JSON_RESPONSE_KEY_ERRORMSG, "原密码输入错误");
            JSONUtils.toJson(response, map);
            return;
        }

        user.setPassword(newpwd);

        service.update(user);

        map.put(Constants.JSON_RESPONSE_KEY_STATUS, "ok");
        map.put(Constants.JSON_RESPONSE_KEY_ERRORMSG, "修改成功");
        JSONUtils.toJson(response, map);

    }

    /**
     * 登录
     *
     * @param request
     * @param response
     */
    private void login(HttpServletRequest request, HttpServletResponse response) {
        HashMap<String, String> map = new HashMap<String, String>();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String vcode = request.getParameter("vcode");
        if (StringUtils.isNullOrEmpty(username)) {
            map.put(Constants.JSON_RESPONSE_KEY_ERRORMSG, "用户名不能为空");
            map.put(Constants.JSON_RESPONSE_KEY_STATUS, "error");
            JSONUtils.toJson(response, map);
            return;
        }
        if (StringUtils.isNullOrEmpty(password)) {
            map.put(Constants.JSON_RESPONSE_KEY_ERRORMSG, "密码不能为空");
            map.put(Constants.JSON_RESPONSE_KEY_STATUS, "error");
            JSONUtils.toJson(response, map);
            return;
        }

        HttpSession session = request.getSession();
        String scode = (String) session.getAttribute("vcode");
        if (!scode.equals(vcode)) {
            map.put(Constants.JSON_RESPONSE_KEY_ERRORMSG, "验证码输入错误");
            map.put(Constants.JSON_RESPONSE_KEY_STATUS, "error");
            JSONUtils.toJson(response, map);
            return;
        }


        Users user = service.login(username, password);
        if (user == null) {
            map.put(Constants.JSON_RESPONSE_KEY_ERRORMSG, "用户名或者密码错误");
            map.put(Constants.JSON_RESPONSE_KEY_STATUS, "error");
            JSONUtils.toJson(response, map);
            return;
        }

        String remeber = request.getParameter("remeber");
        Cookie cookie = new Cookie(Constants.COOKIES_REMEBER_USERNAME, username);

        if ("1".equalsIgnoreCase(remeber)) {
            cookie.setMaxAge(60 * 24 * 7);
            response.addCookie(cookie);
        } else {
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }

        map.put(Constants.JSON_RESPONSE_KEY_ERRORMSG, "登录成功");
        map.put(Constants.JSON_RESPONSE_KEY_STATUS, "ok");
        JSONUtils.toJson(response, map);

        session.setAttribute(Constants.SESSION_USER_MODEL, user);
    }
}
